package com.eastedu.report.client.file;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.eastedu.exception.ServiceException;
import com.eastedu.report.common.property.AliCloudOssProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.Environment;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;


/**
 * The type File ali cloud upload service.
 *
 * @author superman
 */
@Slf4j
public class AliCloudFileUploadServiceImpl implements FileUploadService {

    private final AliCloudOssProperties properties;
    private final Environment environment;
    /**
     * 10年
     */
    public static Long TIME_BETWEEN_FAILURES = 3600L * 1000 * 24 * 365 * 10;

    /**
     * Instantiates a new Ali cloud file upload service.
     *
     * @param properties  the properties
     * @param environment the environment
     */
    public AliCloudFileUploadServiceImpl(AliCloudOssProperties properties, Environment environment) {
        this.properties = properties;
        this.environment = environment;
    }

    @Override
    public String upload(String prefix, File file) throws Exception {
        return this.upload(prefix, file.getName(), Files.newInputStream(file.toPath()));
    }

    @Override
    public String upload(String prefix, String filename, InputStream inputStream) {
        if (Objects.isNull(inputStream)) {
            throw new ServiceException("上传的文件不能为空!");
        }
        String env = determinedEnv();
        String path = Paths.get("report", env, this.determinedPrefix(prefix), filename).toString();
        OSS ossClient = new OSSClientBuilder().build(properties.getEndpoint(), properties.getAccessKeyId(), properties.getAccessKeySecret());
        try {
            log.debug("[{}]上传文件到阿里云OSS, 文件路径:{}", prefix, path);
            ossClient.putObject(properties.getBucketName(), path, inputStream);
            // 获取的http 文件下载地址生效时间 约10年
            Date expiration = new Date(System.currentTimeMillis() + TIME_BETWEEN_FAILURES);
            return ossClient.generatePresignedUrl(properties.getBucketName(), path, expiration).toString();
        } finally {
            ossClient.shutdown();
        }
    }

    private String determinedEnv() {
        String[] profiles = environment.getActiveProfiles();
        return Arrays.stream(profiles).findFirst().orElse(UUID.randomUUID().toString());
    }

    private String determinedPrefix(String prefix) {
        return StringUtils.isBlank(prefix) ? properties.getFileDir() : prefix;
    }
}
